import { http } from '@/utils/request'
import type { IGetDictsRes, DicData } from './type'

const prefix = import.meta.env.VITE_API_SYS

// 根据字典类型查询字典数据信息
export function getDicts(dictType: string): Promise<IGetDictsRes> {
	return new Promise(resolve => {
		http.get<DicData[]>(`${prefix}/dict/data/type/${dictType}`).then(res => {
			const data = res?.data || []
			resolve(
				data.map(v => ({
					label: v.dictLabel,
					value: v.dictValue,
					elTagType: v.listClass,
					elTagClass: v.cssClass
				}))
			)
		})
	})
}

// 获取级联字典
export function getDictsByTypeTree(dictType: string): Promise<IGetDictsRes> {
	return new Promise(resolve => {
		http.get<DicData[]>(`${prefix}/dict/data/cascade/${dictType}`).then(res => {
			const data = res?.data || []
			const transformData = (items: DicData[]): IGetDictsRes => {
				return items.map(v => ({
					label: v.dictLabel,
					value: v.dictValue,
					elTagType: v.listClass,
					elTagClass: v.cssClass,
					children: v.children ? transformData(v.children) : undefined
				}))
			}
			resolve(transformData(data))
		})
	})
}
